package com.m4399.shortcut_test.setting

import android.annotation.SuppressLint
import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import com.wzw.shortcuthelper.core.helper.PermissionRequest
import java.lang.reflect.InvocationTargetException

object ShortcutPermissionChecker {
    private const val TAG = "ShortcutPermissionCheck"
    fun checkOnEMUI(context: Context?): Int {
        Log.d(TAG, "checkOnEMUI")
        val intent = Intent("com.android.launcher.action.INSTALL_SHORTCUT")
        return try {
            val PermissionManager = try {
                Class.forName("com.huawei.hsm.permission.PermissionManager")
            } catch (e: ClassNotFoundException) {
                Class.forName("com.hihonor.hsm.permission.PermissionManager")
            }

            val canSendBroadcast = PermissionManager.getDeclaredMethod(
                "canSendBroadcast", Context::class.java, Intent::class.java
            )
            val invoke = canSendBroadcast.invoke(PermissionManager, context, intent)
            if (invoke != null) {
                val invokeResult = invoke as Boolean
                Log.d(TAG, "EMUI check permission canSendBroadcast invoke result = $invokeResult")
                if (invokeResult) {
                    ShortcutPermission.PERMISSION_GRANTED
                } else {
                    ShortcutPermission.PERMISSION_DENIED
                }
            } else {
                ShortcutPermission.PERMISSION_UNKNOWN
            }
        } catch (e: NoSuchMethodException) {
            Log.d(TAG, e.message, e)
            ShortcutPermission.PERMISSION_UNKNOWN
        } catch (e: IllegalAccessException) {
            Log.d(TAG, e.message, e)
            ShortcutPermission.PERMISSION_UNKNOWN
        } catch (e: InvocationTargetException) {
            Log.d(TAG, e.message, e)
            ShortcutPermission.PERMISSION_UNKNOWN
        } catch (e: Exception) {
            Log.d(TAG, e.message, e)
            ShortcutPermission.PERMISSION_UNKNOWN
        }
    }

    fun checkHMS(): Int {
        try {
            val PermissionManager = Class.forName("com.huawei.hsm.permission.PinShortcutPermission")
            val allowOp = PermissionManager.getDeclaredMethod("allowOp")
            val invoke = allowOp.invoke(PermissionManager)
            return if (invoke != null) {
                val invokeResult = invoke as Boolean
                Log.d(TAG, "EMUI check permission canSendBroadcast invoke result = $invokeResult")
                if (invokeResult) {
                    ShortcutPermission.PERMISSION_GRANTED
                } else {
                    ShortcutPermission.PERMISSION_DENIED
                }
            } else {
                ShortcutPermission.PERMISSION_UNKNOWN
            }
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        }
        return ShortcutPermission.PERMISSION_DENIED
    }

    fun checkOnVIVO(context: Context): Int {
        Log.d(TAG, "checkOnVIVO")
        val contentResolver = context.contentResolver
        if (contentResolver == null) {
            Log.d(TAG, "contentResolver is null")
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        var query: Cursor? = null
        try {
            val parse = Uri.parse("content://com.bbk.launcher2.settings/favorites")
            query = contentResolver.query(parse, null, null, null, null)
            if (query == null) {
                Log.d(TAG, "cursor is null (Uri : content://com.bbk.launcher2.settings/favorites)")
                return ShortcutPermission.PERMISSION_UNKNOWN
            }
            while (query.moveToNext()) {
                val titleByQueryLauncher = query.getString(query.getColumnIndexOrThrow("title"))
                if (!TextUtils.isEmpty(titleByQueryLauncher) && titleByQueryLauncher == getAppName(
                        context
                    )
                ) {
                    val value = query.getInt(query.getColumnIndexOrThrow("shortcutPermission"))
                    Log.d(TAG, "permission value is $value")
                    when (value) {
                        1, 17 -> {
                            return ShortcutPermission.PERMISSION_DENIED
                        }
                        16 -> {
                            return ShortcutPermission.PERMISSION_GRANTED
                        }
                        18 -> {
                            return ShortcutPermission.PERMISSION_ASK
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return ShortcutPermission.PERMISSION_EXCEPTION
        } finally {
            query?.close()
        }
        return ShortcutPermission.PERMISSION_UNKNOWN
    }

    fun checkOn360(context: Context): Int {
        Log.d(TAG, "checkOnVIVO")
        val contentResolver = context.contentResolver
        if (contentResolver == null) {
            Log.d(TAG, "contentResolver is null")
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        var query: Cursor? = null
        try {
            val parse = Uri.parse("content://com.android.launcher3.settings/favorites")
            query = contentResolver.query(parse, null, null, null, null)
            if (query == null) {
                Log.d(TAG, "cursor is null (Uri : content://com.qiku.android.launcher3.settings/favorites)")
                return ShortcutPermission.PERMISSION_UNKNOWN
            }
            while (query.moveToNext()) {
                val titleByQueryLauncher = query.getString(query.getColumnIndexOrThrow("title"))
                if (!TextUtils.isEmpty(titleByQueryLauncher) && titleByQueryLauncher == getAppName(
                        context
                    )
                ) {
                    val value = query.getInt(query.getColumnIndexOrThrow("shortcutPermission"))
                    Log.d(TAG, "permission value is $value")
                    if (value == 1 || value == 17) {
                        return ShortcutPermission.PERMISSION_DENIED
                    } else if (value == 16) {
                        return ShortcutPermission.PERMISSION_GRANTED
                    } else if (value == 18) {
                        return ShortcutPermission.PERMISSION_ASK
                    }
                }
            }
        } catch (e: Exception) {
            return ShortcutPermission.PERMISSION_EXCEPTION
        } finally {
            query?.close()
        }
        return ShortcutPermission.PERMISSION_UNKNOWN
    }

    fun checkNubia(context: Context): Int {
        Log.d(TAG, "checkNubia")
        try {
            val mAppOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
            val pkg = context.applicationContext.packageName
            val uid = context.applicationInfo.uid
            val appOpsClass = Class.forName(AppOpsManager::class.java.name)
            val checkOpNoThrowMethod = appOpsClass.getDeclaredMethod(
                "checkOpNoThrow", Integer.TYPE, Integer.TYPE, String::class.java
            )

            val invoke = checkOpNoThrowMethod.invoke(
                mAppOps, 71, uid, pkg
            ) //the ops of INSTALL_SHORTCUT is 10017
            if (invoke == null) {
                Log.d(
                    TAG, "nubia check permission checkOpNoThrowMethod(AppOpsManager) invoke result is null"
                )
                return ShortcutPermission.PERMISSION_UNKNOWN
            }
            val result = invoke.toString()
            Log.d(
                TAG, "nubia check permission checkOpNoThrowMethod(AppOpsManager) invoke result = $result"
            )
            when (result) {
                "0" -> return ShortcutPermission.PERMISSION_GRANTED
                "1" -> return ShortcutPermission.PERMISSION_DENIED
                "4" -> return ShortcutPermission.PERMISSION_ASK
            }
        } catch (e: Exception) {
            Log.d(TAG, e.message, e)
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        return ShortcutPermission.PERMISSION_UNKNOWN
    }

    fun checkOnMIUI(context: Context): Int {
        Log.d(TAG, "checkOnMIUI")
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        try {
            val mAppOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
            val pkg = context.applicationContext.packageName
            val uid = context.applicationInfo.uid
            val appOpsClass = Class.forName(AppOpsManager::class.java.name)
            val checkOpNoThrowMethod = appOpsClass.getDeclaredMethod(
                "checkOpNoThrow", Integer.TYPE, Integer.TYPE, String::class.java
            )
            val invoke = checkOpNoThrowMethod.invoke(
                mAppOps, 10017, uid, pkg
            ) //the ops of INSTALL_SHORTCUT is 10017
            if (invoke == null) {
                Log.d(
                    TAG, "MIUI check permission checkOpNoThrowMethod(AppOpsManager) invoke result is null"
                )
                return ShortcutPermission.PERMISSION_UNKNOWN
            }
            val result = invoke.toString()
            Log.d(TAG, "MIUI check permission checkOpNoThrowMethod(AppOpsManager) invoke result = $result")
            when (result) {
                "0" -> return ShortcutPermission.PERMISSION_GRANTED
                "1" -> return ShortcutPermission.PERMISSION_DENIED
                "5" -> return ShortcutPermission.PERMISSION_ASK
            }
        } catch (e: Exception) {
            Log.d(TAG, e.message, e)
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        return ShortcutPermission.PERMISSION_UNKNOWN
    }


    fun checkOnOPPO(context: Context): Int {
        Log.d(TAG, "checkOnOPPO")
        val contentResolver = context.contentResolver
        if (contentResolver == null) {
            Log.d(TAG, "contentResolver is null")
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        val parse = Uri.parse("content://settings/secure/launcher_shortcut_permission_settings")
        val query = contentResolver.query(parse, null, null, null, null)
        if (query == null) {
            Log.d(
                TAG, "cursor is null (Uri : content://settings/secure/launcher_shortcut_permission_settings)"
            )
            return ShortcutPermission.PERMISSION_UNKNOWN
        }
        return try {
            val pkg = context.applicationContext.packageName.removeSuffix(".shell")

            while (query.moveToNext()) {
                @SuppressLint("Range") val value = query.getString(query.getColumnIndex("value"))
                Log.d(TAG, "permission value is $value")
                if (!TextUtils.isEmpty(value)) {
                    if (value.contains("$pkg, 1")) {
                        return ShortcutPermission.PERMISSION_GRANTED
                    }
                    if (value.contains("$pkg, 0")) {
                        //oppo bug
                        Log.d(TAG, "checkOnOPPO: value: $value")
                        val intent = PermissionRequest(context).oppoApi(context)
                        if (context == context.applicationContext) {
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        }
                        try {
                            Log.d("shortcut", "Intent: $intent")

                            val resolveActivity = context.packageManager.resolveActivity(intent, 0)
                            Log.d(TAG, "checkOnOPPO: $resolveActivity")
                            //  context.startActivity(intent)

                            return ShortcutPermission.PERMISSION_UNKNOWN
                        } catch (e: Exception) {
                            Log.d(TAG, "checkOnOPPO: oppo bug 如果无法跳转授权页就给unknown")
                            e.printStackTrace()
                            return ShortcutPermission.PERMISSION_UNKNOWN
                        }

                    }
                }
            }
            ShortcutPermission.PERMISSION_UNKNOWN
        } catch (e: Exception) {
            Log.d(TAG, e.message, e)
            ShortcutPermission.PERMISSION_UNKNOWN
        } finally {
            query.close()
        }
    }

    private fun getAppName(context: Context): String? {
        return try {
            val pm = context.packageManager
            val pi = pm.getPackageInfo(context.applicationContext.packageName, 0)
            pi?.applicationInfo?.loadLabel(pm)?.toString()
        } catch (e: PackageManager.NameNotFoundException) {
            ""
        }
    }
}